package com.nth.android.ar;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.location.Location;
import android.view.MotionEvent;

public abstract class ARItemizedOverlay extends AROverlay {

	private Bitmap itemBackground;
	private Paint paint;

	public ARItemizedOverlay(Context context, int itemBackgroundResourceId) {
		super();
		itemBackground = BitmapFactory.decodeResource(context.getResources(), itemBackgroundResourceId);
		paint = new Paint();
		paint.setColor(Color.BLACK);
		paint.setTextSize(25);
		paint.setTextAlign(Align.CENTER);
		paint.setStyle(Paint.Style.FILL);
		paint.setAntiAlias(true);
	}

	protected abstract AROverlayItem getItem(int index);

	protected abstract int size();

	protected boolean onTap(int index) {
		return false;
	}

	protected boolean onTouch(MotionEvent event) {
		AROverlayItem item;
		Vector3 markerPosition;

		for (int i = 0; i < size(); i++) {
			item = getItem(i);
			if (item.isVisible()) {
				markerPosition = item.getcMarker();
				int xSpan = (int) (markerPosition.x - event.getX());
				int ySpan = (int) (markerPosition.y - event.getY());
				if (Math.abs(xSpan) < getItemBackground().getWidth() / 2 && ySpan > 0 && ySpan < getItemBackground().getHeight()) {
					if (onTap(i)) return true;
				}
			}
		}
		return false;
	}

	public Bitmap getItemBackground() {
		return itemBackground;
	}

	public void setItemBackground(Bitmap itemBackground) {
		this.itemBackground = itemBackground;
	}

	public void locationUpdated(Location location) {
		for (int i = 0; i < size(); i++) {
			getItem(i).locationUpdated(location);
		}
	}

	public double getMaxDistance() {
		double maxDistance = 0;
		for (int i = 0; i < size(); i++) {
			if (maxDistance < getItem(i).getDistance()) {
				maxDistance = getItem(i).getDistance();
			}
		}
		return maxDistance;
	}

	@Override
	protected void calcAndDraw(Canvas canvas, ARCamera viewCam, float addX, float addY, float curBearing) {
		AROverlayItem item;
		Vector3 markerPosition;

		for (int i = 0; i < size(); i++) {
			item = getItem(i);
			item.calc(viewCam, addX, addY);
			markerPosition = item.getcMarker();

			if (item.isVisible()) {
				canvas.save();
				canvas.translate(markerPosition.x, markerPosition.y);
				drawItem(canvas, item);
				canvas.restore();
			}
		}
	}

	protected void drawItem(Canvas canvas, AROverlayItem item) {
		canvas.drawBitmap(getItemBackground(), -getItemBackground().getWidth() / 2, -getItemBackground().getHeight(), null);
		canvas.drawText(item.getTitle(), 0, paint.getTextSize(), paint);
	}

}
